import React, { useEffect, useState } from 'react';
import { XfVoiceDictation } from '@muguilin/xf-voice-dictation';
import audio from '@/static/imgs/audio.png';
import './index.scss';

let times: any = null;

interface AudioProps {
  onTextChange: (text: string) => void;
  width: string;
  handleSend: () => void
}

let xfVoice: XfVoiceDictation | null = null;

function Audio({ onTextChange, width, handleSend }: AudioProps) {
  const [recordingStatus, setRecordingStatus] = useState('end');

  const style = { width, height: width };

  useEffect(() => {
    xfVoice = new XfVoiceDictation({
      APPID: 'b3d77053',
      APISecret: 'NDU0ZThjNzUwNmEzNjZkNDE3Yjc5ZDFi',
      APIKey: '966108da7c1b9c8cee68a8fcb05255bc',
      // webSocket请求地址 非必传参数，默认为：wss://iat-api.xfyun.cn/v2/iat
      // url: '',

      // 监听录音状态变化回调
      onWillStatusChange(oldStatus: any, newStatus: any) {
        // 可以在这里进行页面中一些交互逻辑处理：注：倒计时（语音听写只有60s）,录音的动画，按钮交互等！
        console.log('识别状态：', oldStatus, newStatus);
        setRecordingStatus(newStatus);
      },

      // 监听识别结果的变化回调
      onTextChange(text: any) {
        // 可以在这里进行页面中一些交互逻辑处理：如将文本显示在页面中
        console.log('识别内容：', text);
        onTextChange?.(text);
        // handleSend?.();
        // 如果3秒钟内没有说话，就自动关闭（60s后也会自动关闭）
        if (text) {
          console.log('进入了执行3s关闭');
          clearTimeout(times);
          times = setTimeout(() => {
            // handleSend?.();
            xfVoice?.stop();
          }, 3000);
        }
      },

      // 监听识别错误回调
      onError(error: any) {
        console.log('错误信息：', error);
      },
    });
  }, []);
  const recording = () => {
    // 开始录音
    recordingStatus === 'end' && xfVoice?.start();
  };
  return (
    <div className="audio" onClick={recording}>
      <div className={recordingStatus === 'ing' ? 'fixed-icon' : 'recording-icon'} style={style}>
        <img style={style} src={audio} alt="" />
      </div>
    </div>
  );
}

export default Audio;
